package ptkdemo.client;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.ui.*;
import com.googlecode.gwtptk.client.AlertAsyncCallback;
import com.googlecode.gwtptk.client.DataTable;
import com.googlecode.gwtptk.client.PageOf;

/**
 * SimpleScreen.
 *
 * @author Richard "Virgo" Richter (virgo47@gmail.com)
 */
public class SimpleScreen extends Composite {
	private UserDataTable table = new UserDataTable();
	private UserFilter filter = new UserFilter();
	private PageOf<User> page;

	private Label searchLink;
	private TextBox inputName;
	private PtkDemo module;

	public SimpleScreen(PtkDemo pmodule) {
		module = pmodule;
		VerticalPanel panel = new VerticalPanel();
		panel.setSpacing(8);
		Label title = new Label("User list");
		title.addStyleName("title");
		panel.add(title);
		panel.add(createFilterPanel());
		panel.add(table);
		initWidget(panel);
		callRefresh();
	}

	private Grid createFilterPanel() {
		final Grid filterPanel = new Grid(2, 5);
		filterPanel.setText(0, 0, "Name");

		inputName = new TextBox();
		inputName.setWidth("120px");
		filterPanel.setWidget(1, 0, inputName);

		searchLink = new Label("?");
		searchLink.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				startSearch(inputName);
			}
		});
		filterPanel.setWidget(1, 4, searchLink);

		KeyPressHandler enterHandler = new KeyPressHandler() {
			@Override
			public void onKeyPress(KeyPressEvent keyPressEvent) {
				if (keyPressEvent.getCharCode() == 13) {
					startSearch(inputName);
				}
			}
		};
		inputName.addKeyPressHandler(enterHandler);
		return filterPanel;
	}

	private void startSearch(TextBox inputName) {
		filter.clear();
		filter.setName(inputName.getValue());
		callRefresh();
	}

	void callRefresh() {
		searchLink.setText("...working");
		searchLink.removeStyleName("link");
		module.getService().listUsers(filter, new AlertAsyncCallback<PageOf<User>>() {
			@Override
			public void onSuccess(PageOf<User> data) {
				page = data;
				refreshTable();
				searchLink.setText("Search");
				searchLink.addStyleName("link");
				inputName.setFocus(true);
			}
		});
	}

	private void refreshTable() {
		table.clear();
		if (page != null && page.getList() != null) {
			for (final User user : page.getList()) {
				table.addRow(user.getName(),
					user.getAddress(),
					user.getEmail(),
					user.getNote());
			}
		}
	}

	private class UserDataTable extends DataTable {
		private UserDataTable() {
			defineColumns(new DataColumn("Name"),
				new DataColumn("Address"),
				new DataColumn("E-mail"),
				new DataColumn("Note"));
		}
	}
}
